$(function () {
  initArtCateList();
  var layer = layui.layer;
  var form = layui.form;
  // 获取文章分类的列表
  function initArtCateList() {
    $.ajax({
      method: "GET",
      url: "/my/article/cates",
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg("文章请求失败");
        }
        // console.log(res);
        var htmlTpl = template("tpl-table", res);
        $("tbody").html(htmlTpl);
      },
    });
  }
  var indexAdd = null;
  // 给添加类别按钮绑定点击事件
  $("#btnAdd").on("click", function () {
    indexAdd = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "添加文章分类",
      content: $("#dialog-add").html(),
    });
  });
  $("body").on("submit", "#form-add", function (e) {
    e.preventDefault();
    $.ajax({
      method: "POST",
      url: "/my/article/addcates",
      data: $(this).serialize(),
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg("添加图书失败");
        }
        layer.msg("添加成功");
        initArtCateList();
      },
    });
    layer.close(indexAdd);
  });
  // 为编辑文章分类添加监听事件
  var indexS = null;
  $("tbody").on("click", ".btn-j", function () {
    indexS = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "修改文章分类",
      content: $("#diaS-add").html(),
    });
    var id = $(this).attr("data-Id");
    // console.log(id);
    $.ajax({
      method: "GET",
      url: "/my/article/cates/" + id,
      success: function (res) {
        console.log(res);
        form.val("formUserInfo", res.data);
      },
    });
  });

  // 为提交按钮添加监听事件
  $("body").on("submit", "#form-S", function (e) {
    e.preventDefault();

    $.ajax({
      method: "POST",
      url: "/my/article/updatecate",
      data: $(this).serialize(),
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg("更新分类数据失败");
        }
        layer.msg("更新分类数据成功");
        initArtCateList();
      },
    });
    layer.close(indexS);
  });

  // //为删除按钮绑定事件
  $("body").on("click", ".btn-s", function (e) {
    var id = $(this).attr("data-id");
    layer.confirm("确认删除?", { icon: 3, title: "提示" }, function (index) {
      $.ajax({
        method: "GET",
        url: "/my/article/deletecate/" + id,
        success: function (res) {
          console.log(res);
          if (res.status !== 0) {
            layer.msg("删除失败");
          }
          layer.msg("删除成功");
          layer.close(index);
          initArtCateList();
        },
      });
    });
  });
});
